﻿using CreateCodeByDatabase.Bll;
using CreateCodeByDatabase.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace CreateCodeByDatabase
{
    public partial class GYDTJ_DYY_PDM_Handler : Form
    {
        IOperate operate { get; set; }
        /// <summary>
        /// 表字典，格式[表名,{列信息}]
        /// </summary>
        private Dictionary<string, List<ColumnInfo>> tableColumnDic;
        /// <summary>
        /// 已读取PDM文件
        /// </summary>
        XmlDocument projectXmlFile;

        public GYDTJ_DYY_PDM_Handler()
        {
            InitializeComponent();
            operate = IOperate.GetOperate();
        }
        private void GYDTJ_DYY_PDM_Handler_Load(object sender, EventArgs e)
        {
            //txtTableName.Text = "t_hj_";
            txtFilePath.Text = @"D:\code\DOC\02.设计文档\02.数据库设计\申洲技术中心管平台-工艺单提交查询多语言.pdm";
            projectXmlFile = GetXmlDocument();
        }

        private void btnSearchPDMFile_Click(object sender, EventArgs e)
        {
            openFileDialog1.AddExtension = true;
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.Filter = "pdm文件|*.pdm";
            openFileDialog1.CheckPathExists = true;
            openFileDialog1.DefaultExt = ".pdm";
            openFileDialog1.InitialDirectory = @"D:\code\DOC\02.设计文档\02.数据库设计";
            if (openFileDialog1.ShowDialog() != DialogResult.OK)
                return;
            txtFilePath.Text = openFileDialog1.FileName;
            projectXmlFile = GetXmlDocument();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            if (projectXmlFile == null)
            {
                MessageBox.Show("载入PDM文件失败");
                return;
            }
            tableColumnDic = new Dictionary<string, List<ColumnInfo>>();
            List<TableInfo> tableList = new List<TableInfo>();
            try
            {
                ReadTableInfo(tableColumnDic, tableList);
                //if (tableColumnDic.Count < 1 || tableList.Count < 1)
                //{
                //    MessageBox.Show("读取PDM文件表信息失败");
                //    return;
                //}
                //gridMain.DataSource = tableList;
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                MessageBox.Show("执行异常，详细信息请查看日志");
            }
        }
        /// <summary>
        /// 载入读取PDM文件
        /// </summary>
        /// <returns></returns>
        private XmlDocument GetXmlDocument()
        {
            XmlDocument projectXmlFile = new XmlDocument();
            try
            {
                using (var tempStream = File.Open(txtFilePath.Text,FileMode.Open,FileAccess.Read,FileShare.Read))
                {
                    projectXmlFile.Load(tempStream);
                }
                return projectXmlFile;
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                return null;
            }
        }
        /// <summary>
        /// 读取表信息
        /// </summary>
        /// <param name="projectXmlFile"></param>
        /// <param name="tableColumnDic"></param>
        /// <param name="tableList"></param>
        private void ReadTableInfo(Dictionary<string, List<ColumnInfo>> tableColumnDic, List<TableInfo> tableList)
        {
            string queryCondition = txtTableName.Text.Trim().ToUpper();
            //项目文档中使用了命名空间 ，使用XPath时 只有包含命名空间信息才可查询到节点信息
            string xPath = @"/Model/o:RootObject/c:Children/o:Model/c:Tables";
            //string xPath = @"o:RootObject/c:Children/o:Model/c:Tables";
            XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(projectXmlFile.NameTable);
            nsmgr.AddNamespace("c", "collection");
            nsmgr.AddNamespace("o", "object");
            nsmgr.AddNamespace("a", "attribute");

            XmlNode tablesNode = projectXmlFile.DocumentElement.SelectSingleNode(xPath, nsmgr);
            if (tablesNode == null || tablesNode.ChildNodes == null || tablesNode.ChildNodes.Count < 1)
            {
                MessageBox.Show("读取PDM文件表节点失败");
                return;
            }

            List<string> errorList = new List<string>();
            int tempErrorCount = 0;
            string tempxPath = null;
            string tempTableName = null;
            int tempId = 56;
            string tempType = null;
            foreach (XmlNode itemTable in tablesNode.ChildNodes)
            {
                tempxPath = "a:Code";
                System.Xml.XmlNode tableNameNode = itemTable.SelectSingleNode(tempxPath, nsmgr);
                tempTableName = tableNameNode.InnerText.ToUpper();
                if (!string.IsNullOrWhiteSpace(queryCondition) && !tempTableName.StartsWith(queryCondition))
                    continue;

                tempxPath = "c:Columns";
                XmlNode ColumnNodeParent = itemTable.SelectSingleNode(tempxPath, nsmgr);
                List<string> tempIdList = new List<string>();
                foreach (XmlNode itemColumn in ColumnNodeParent.ChildNodes)
                {
                    tempxPath = "a:ObjectID";
                    System.Xml.XmlNode columnIdNode = itemColumn.SelectSingleNode(tempxPath, nsmgr);
                    if (tempIdList.Contains(columnIdNode.InnerText))
                        continue;

                    itemColumn.Attributes["Id"].Value = "o" + (tempId++).ToString();
                    tempxPath = "a:DataType";
                    System.Xml.XmlNode columnDataTypeNode = itemColumn.SelectSingleNode(tempxPath, nsmgr);
                    
                    if (columnDataTypeNode != null && columnDataTypeNode.InnerText.ToUpper().StartsWith("VARCHAR"))
                    {
                        tempType = columnDataTypeNode.InnerText;
                        if( !string.IsNullOrWhiteSpace(tempType) )
                        {
                            tempType = tempType.Trim().ToUpper();
                            if(tempType.StartsWith("VARCHAR"))
                            {
                                tempType = tempType.Replace("VARCHAR","NVARCHAR");
                                columnDataTypeNode.InnerText = tempType;
                            }
                        }
                    }
                    var copyColumn = itemColumn.Clone();
                    copyColumn.Attributes["Id"].Value = "o" + (tempId++).ToString();
                    tempxPath = "a:ObjectID";

                    columnIdNode = copyColumn.SelectSingleNode(tempxPath, nsmgr);
                    columnIdNode.InnerText = Guid.NewGuid().ToString().ToUpper();
                    tempIdList.Add(columnIdNode.InnerText);
                    tempxPath = "a:Code";
                    System.Xml.XmlNode columnCodeNode = copyColumn.SelectSingleNode(tempxPath, nsmgr);
                    columnCodeNode.InnerText = columnCodeNode.InnerText + "_FY";

                    tempxPath = "a:Name";
                    System.Xml.XmlNode columnNameNode = copyColumn.SelectSingleNode(tempxPath, nsmgr);
                    columnNameNode.InnerText = columnNameNode.InnerText + "_翻译";
                    itemColumn.ParentNode.InsertAfter(copyColumn, itemColumn);
                }
            }
            projectXmlFile.Save(txtFilePath.Text);
            MessageBox.Show("操作结束");
            return;
        }



        private string GetDataType(ColumnInfo column, out string dataLength, out string precision)
        {
            string columnDataType = null;
            dataLength = null;
            precision = null;
            switch (column.DataType)
            {
                case "NVARCHAR2":
                case "CHAR":
                    columnDataType = $"{column.DataType}({column.DataLength})";
                    dataLength = column.DataLength.ToString();
                    break;
                case "DATE":
                    columnDataType = column.DataType;
                    break;
                case "NUMBER":
                    if (column.DataScale.HasValue)
                    {
                        if (column.DataScale.Value > 0)
                        {
                            columnDataType = $"{column.DataType}({column.DataPrecision.Value},{column.DataScale.Value})";
                            dataLength = column.DataPrecision.Value.ToString();
                            precision = column.DataScale.Value.ToString();
                        }
                        else if (column.DataScale.Value == 0)
                        {
                            if (column.DataPrecision.HasValue)
                            {
                                columnDataType = $"{column.DataType}({column.DataPrecision.Value})";
                                dataLength = column.DataPrecision.Value.ToString();
                            }
                            else
                                columnDataType = $"{column.DataType}(INTEGER)";
                        }
                    }
                    else
                        throw new Exception(column.ColumnName + "数据类型异常");
                    break;
                default:
                    throw new Exception(column.ColumnName + "数据类型遗漏");
                    break;
            }
            return columnDataType;
        }
        /// <summary>
        /// 翻译管理表名处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void button1_Click(object sender, EventArgs e)
        //{
        //    if (projectXmlFile == null)
        //    {
        //        MessageBox.Show("载入PDM文件失败");
        //        return;
        //    }
        //    try
        //    {
        //        string queryCondition = txtTableName.Text.Trim().ToUpper();
        //        //项目文档中使用了命名空间 ，使用XPath时 只有包含命名空间信息才可查询到节点信息
        //        string xPath = @"/Model/o:RootObject/c:Children/o:Model/c:Tables";
        //        //string xPath = @"o:RootObject/c:Children/o:Model/c:Tables";
        //        XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(projectXmlFile.NameTable);
        //        nsmgr.AddNamespace("c", "collection");
        //        nsmgr.AddNamespace("o", "object");
        //        nsmgr.AddNamespace("a", "attribute");

        //        XmlNode tablesNode = projectXmlFile.DocumentElement.SelectSingleNode(xPath, nsmgr);
        //        if (tablesNode == null || tablesNode.ChildNodes == null || tablesNode.ChildNodes.Count < 1)
        //        {
        //            MessageBox.Show("读取PDM文件表节点失败");
        //            return;
        //        }

        //        List<string> errorList = new List<string>();
        //        int tempErrorCount = 0;
        //        string tempxPath = null;
        //        string tempTableName = null;
        //        int tempId = 56;
        //        string tempType = null;
        //        List<string> tableNameList = new List<string>();
        //        foreach (XmlNode itemTable in tablesNode.ChildNodes)
        //        {
        //            tempxPath = "a:Code";
        //            System.Xml.XmlNode tableNameNode = itemTable.SelectSingleNode(tempxPath, nsmgr);
        //            // JSZX_GYD_FYGL_YHYQ
        //            // JSZX_GYD_TJ_MLXX
        //            tempTableName = tableNameNode.InnerText.ToUpper();
        //            if (!string.IsNullOrWhiteSpace(queryCondition) && !tempTableName.StartsWith(queryCondition))
        //                continue;
        //            if(tempTableName == "JSZX_GYD_TJ")
        //            {
        //                tempTableName = "JSZX_GYD_FYGL_GYD";
        //            }
        //            else if(tempTableName.Contains("JSZX_GYD_TJ_"))
        //            {
        //                tempTableName = tempTableName.Replace("JSZX_GYD_TJ_", "JSZX_GYD_FYGL_");
        //            }
        //            else
        //            {
        //                tableNameList.Add(tempTableName);
        //                continue;
        //            }
        //            tempTableName = tempTableName.Replace("JSZX_GYD_TJ_", "JSZX_GYD_FYGL_");
        //            tableNameNode.InnerText = tempTableName;

        //            tempxPath = "a:Name";
        //            System.Xml.XmlNode tableCommentNode = itemTable.SelectSingleNode(tempxPath, nsmgr);
        //            tempTableName = tableCommentNode.InnerText;
        //            if (tempTableName.Contains("工艺单提交"))
        //                tempTableName = tempTableName.Replace("工艺单提交", "翻译管理_");
        //            tableCommentNode.InnerText = tempTableName;

        //            tempxPath = "a:Comment";
        //            System.Xml.XmlNode tableComment2Node = itemTable.SelectSingleNode(tempxPath, nsmgr);
        //            if(tableComment2Node == null)
        //            {
        //                tableComment2Node = projectXmlFile.CreateElement(tempxPath, "a");
        //                itemTable.AppendChild(tableComment2Node);
        //            }
        //            tableComment2Node.InnerText = tempTableName;
        //        }
        //        projectXmlFile.Save(txtFilePath.Text);
        //        richTextBox1.Text = String.Join(Environment.NewLine, tableNameList);
        //        MessageBox.Show("操作结束");
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.WriteLog(ex);
        //        MessageBox.Show("执行异常，详细信息请查看日志");
        //    }
        //}
        // 翻译提交表名处理
        private void button1_Click(object sender, EventArgs e)
        {
            if (projectXmlFile == null)
            {
                MessageBox.Show("载入PDM文件失败");
                return;
            }
            try
            {
                string queryCondition = txtTableName.Text.Trim().ToUpper();
                //项目文档中使用了命名空间 ，使用XPath时 只有包含命名空间信息才可查询到节点信息
                string xPath = @"/Model/o:RootObject/c:Children/o:Model/c:Tables";
                //string xPath = @"o:RootObject/c:Children/o:Model/c:Tables";
                XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(projectXmlFile.NameTable);
                nsmgr.AddNamespace("c", "collection");
                nsmgr.AddNamespace("o", "object");
                nsmgr.AddNamespace("a", "attribute");

                XmlNode tablesNode = projectXmlFile.DocumentElement.SelectSingleNode(xPath, nsmgr);
                if (tablesNode == null || tablesNode.ChildNodes == null || tablesNode.ChildNodes.Count < 1)
                {
                    MessageBox.Show("读取PDM文件表节点失败");
                    return;
                }

                List<string> errorList = new List<string>();
                int tempErrorCount = 0;
                string tempxPath = null;
                string tempTableName = null;
                int tempId = 56;
                string tempType = null;
                List<string> tableNameList = new List<string>();
                foreach (XmlNode itemTable in tablesNode.ChildNodes)
                {
                    tempxPath = "a:Code";
                    System.Xml.XmlNode tableNameNode = itemTable.SelectSingleNode(tempxPath, nsmgr);
                    // JSZX_GYD_FYGL_YHYQ
                    // JSZX_GYD_TJ_MLXX
                    tempTableName = tableNameNode.InnerText.ToUpper();
                    if (!string.IsNullOrWhiteSpace(queryCondition) && !tempTableName.StartsWith(queryCondition))
                        continue;
                    //if(tempTableName == "JSZX_GYD_TJ")
                    //{
                    //    tempTableName = "JSZX_GYD_FYGL_GYD";
                    //}
                    //else if(tempTableName.Contains("JSZX_GYD_TJ_"))
                    //{
                    //    tempTableName = tempTableName.Replace("JSZX_GYD_TJ_", "JSZX_GYD_FYGL_");
                    //}
                    //else
                    //{
                    //    tableNameList.Add(tempTableName);
                    //    continue;
                    //}
                    tempTableName = tempTableName.Replace("FYGL", "FYTJ");
                    tableNameNode.InnerText = tempTableName;

                    tempxPath = "a:Name";
                    System.Xml.XmlNode tableCommentNode = itemTable.SelectSingleNode(tempxPath, nsmgr);
                    tempTableName = tableCommentNode.InnerText;
                    tempTableName = tempTableName.Replace("翻译管理", "翻译提交");
                    tableCommentNode.InnerText = tempTableName;

                    tempxPath = "a:Comment";
                    System.Xml.XmlNode tableComment2Node = itemTable.SelectSingleNode(tempxPath, nsmgr);
                    if (tableComment2Node == null)
                    {
                        tableComment2Node = projectXmlFile.CreateElement(tempxPath, "a");
                        itemTable.AppendChild(tableComment2Node);
                    }
                    tableComment2Node.InnerText = tempTableName;
                }
                projectXmlFile.Save(txtFilePath.Text);
                richTextBox1.Text = String.Join(Environment.NewLine, tableNameList);
                MessageBox.Show("操作结束");
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                MessageBox.Show("执行异常，详细信息请查看日志");
            }
        }
    }
}
